package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//import com.cteckmalls.base.tools.ConfigUtil;
//import com.cteckmalls.base.tools.http.utils.DateUtil;
//import com.cteckmalls.base.tools.http.utils.Logger;
//import com.cteckmalls.base.tools.http.utils.MD5;
//
//import com.cteckmalls.interfaces.domain.CuccOrderSend;
import net.sf.json.JSONObject;
import util.date.DateUtil;

/**
 * @author 赵龙
 * 修改人：
 * 修改时间：2016-11-16
 */
public class HttpServiceUtil {
	
	/**
	 * 	2.1	获取验购系统Authorization Code
	 */
	public  static String remoteCallHttpServletPost(String wmsCallUrl, Map<String, String> parameters) {
		//logBefore(logger, "进入HttpUtil.remoteCallHttpServlet()====================================");
		// 返回的结果 
		StringBuilder result = new StringBuilder();
		// 读取响应输入流
		BufferedReader in = null;
		// post参数写入流
		PrintWriter out = null;
		// 处理请求参数
		StringBuffer sb = new StringBuffer();
		// 编码之后的参数
		String params = "";
	try {
			// 编码请求参数
			if (parameters.size() == 1) {
				for (String name : parameters.keySet()) {
					sb.append(name)
							.append("=")
							.append(URLEncoder.encode(
									parameters.get(name), "UTF-8"));
				}
				params = sb.toString();
			} else {
				for (String name : parameters.keySet()) {
					sb.append(name)
							.append("=")
							.append(URLEncoder.encode(
									parameters.get(name), "UTF-8")).append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
			URL pageUrl = new URL(wmsCallUrl);
			HttpURLConnection httpConn = (HttpURLConnection) pageUrl.openConnection();
			httpConn.setRequestProperty("Accept", "*/*");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
			//httpPost.setRequestProperty("x-forwarded-for","116.199.2.208");
			//身份验证 :(账号:username 密码：123)加密后的值=Basic dXNlcm5hbWU6MTIz
			//httpConn.setRequestProperty("Authorization", "Basic dXNlcm5hbWU6MTIz");
			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			// 获取HttpURLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			boolean s=true;
			while (s) {
			out.write(params);
			//Thread.sleep(Long.valueOf(2000));
			//System.out.print("2");
				s=false;
			}
			out.flush();
			out.close();
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式  
	        in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
	        String line;
	        // 读取返回的内容  
	        while ((line = in.readLine()) != null) {  
	            result.append(line) ;  
	        }
	        in.close();
			httpConn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();

		} catch (ProtocolException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		} catch (Exception e) {
		e.printStackTrace();
	}
		//logBefore(logger, "调用接口返回结果：result="+result.toString());
		return result.toString();
	}
	
	
	public  static String remoteCallHttpServletGet(String wmsCallUrl, Map<String, String> parameters) {
		//logBefore(logger, "进入HttpUtil.remoteCallHttpServlet()====================================");
		// 返回的结果 
		StringBuilder result = new StringBuilder();
		// 读取响应输入流
		BufferedReader in = null;
		// post参数写入流
		PrintWriter out = null;
		// 处理请求参数
		StringBuffer sb = new StringBuffer();
		// 编码之后的参数
		String params = "";
		String dateTime=	DateUtil.getTime();
	try {
			// 编码请求参数
			if (parameters.size() == 1) {
				for (String name : parameters.keySet()) {
					sb.append(name)
							.append("=")
							.append(URLEncoder.encode(
									parameters.get(name), "UTF-8"));
				}
				params = sb.toString();
			} else {
				for (String name : parameters.keySet()) {
					sb.append(name)
							.append("=")
							.append(URLEncoder.encode(
									parameters.get(name), "UTF-8")).append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
				URL pageUrl = new URL(wmsCallUrl+"?"+params);
			HttpURLConnection httpConn = (HttpURLConnection) pageUrl.openConnection();
			httpConn.setRequestProperty("Accept", "*/*");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
			//身份验证 :(账号:username 密码：123)加密后的值=Basic dXNlcm5hbWU6MTIz
			httpConn.setRequestProperty("Authorization", "Basic dXNlcm5hbWU6MTIz");
			//GET方式提交
			httpConn.setDoInput(true);
			// 设置POST方式
			//httpConn.setDoOutput(true);
			// 获取HttpURLConnection对象对应的输出流
			//out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			//out.write(params);
			//out.flush();
			//out.close();
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式  
	        in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
	        String line;  
	        // 读取返回的内容  
	        while ((line = in.readLine()) != null) {  
	            result.append(line) ;  
	        }
	        in.close();
			httpConn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//logBefore(logger, "调用接口返回结果：result="+result.toString());
		return result.toString();
	}

	/**
	 *	发送订单(发货单)信息到ESB服务端
	 * @param basecode 基地内码（测试设置徐州中联基地代码1007）
	 * @param ordertime 发货单下单时间
	 * @param customerID 客户（内码）
	 * @param productID	产品sku（内码）
	 * @param num	数量（发货单数量）
	 * @param taxprice  产品含税单价
	 * @param protaxrate 产品税率
	 * @param proamount 产品总金额
	 * @param amountcoll 总金额（包含运费）
	 * @param orderID 订单id
	 * @param orderNo 订单编号
	 * @return 	json字符串
		{
		orderCode:订单编号,
		resultCode:返回数据结果,
		status:返回状态
		}
		成功例子：
	  	{
			"orderCode":"10004",
			"resultCode":"订单10004发送成功",
			"status":"1"
		}
	 */
	public static JSONObject esbOrderSend(String	basecode
												,String	ordertime
												,String	customerID
												,String	productID
												,String	num
												,String	taxprice
												,String	protaxrate
												,String	proamount
												,String	amountcoll
									  			,String orderID
									  			,String orderNo
	) {
		Map<String, String> params2 = new HashMap<String, String>();
		//444是临时数据，后期需要更改
		//必须 密码123
		params2.put("username","123");
		/*
		基地代码/现测试设置徐州中联基地代码1007
		基地代码1008 客户端连接失败
		基地代码1009客户端连接未配置*/
		params2.put("basecode",basecode);


		JSONObject params =new JSONObject();
		//订单时间（发货单时间）DateUtil.getTime())
		params.put("ordertime",ordertime);
		//客户id（内码）
		params.put("customerID",customerID);
		//产品id（内码）
		params.put("productID",productID);
		//数量（发货单数量）
		params.put("num",num);
		//产品不含税单价（暂时不用）
		params.put("notaxprice","444");
		//产品含税单价
		params.put("taxprice",taxprice);
		//产品税率
		params.put("protaxrate",protaxrate);
		//产品税额（暂时不用）
		params.put("protax","444");
		//产品金额
		params.put("proamount",proamount);
		//transprice 运费单价（暂时不用）
		params.put("transprice","444");
		//运费金额（暂时不用）
		params.put("transamount","444");
		//运费税率（暂时不用）
		params.put("transtax","444");
		//现金类科目id 默认值  暂定 1
		params.put("cashID","1");
		//收款金额
		params.put("amountcoll",amountcoll);
		//折扣金额(默认为0)暂时没有折扣
		params.put("discountamount","0");
		//运输方式：汽运，船运
		params.put("transtype","汽运");
		//订单id   必须	订单id
		params.put("orderID",orderID);
		//订单编号 必须	订单编号
		params.put("ordercode",orderNo);

		params2.put("data",params.toString());

		//测试环境地址：http://api.trainer.nbeport.com/router/rest
		//String result =NbeportHttpServiceUtil.remoteCallHttpServletGet(ConfigUtil.getValue("http.url.nbeport"),params);
		String result = HttpServiceUtil.remoteCallHttpServletPost("http://192.168.10.222:5888/http/ordersend",params2);
		//正式环境地址：http://api.nbeport.com/router/rest
		//String result =NbeportHttpServiceUtil.remoteCallHttpServletGet("http://api.nbeport.com/router/rest",params);
		return JSONObject.fromObject(result);
	}


	public volatile static int count = 0;
	public static void inc() {
		//这里延迟1秒，使得结果明显
		try {
			//String result3 = HttpServiceUtil.remoteCallHttpServletPost("http://fum99.com", null);
			//Thread.sleep(3000);
		} catch (Exception e) {
		}
		count++;
	}

	public static void main(String[] args) {
//本地数据库设置
		Map<String, String> params2 = new HashMap<String, String>();
//		params2.put("basecode","1007");			//基地内码
//		params2.put("ordercode","od201706261516369692");	//订单编号(发货单编号)
//		params2.put("FBase2","18956");			//客户内码
//		params2.put("FBase1","18551");				//商品sku内码
//		params2.put("FText","123");			//车号
//		params2.put("FTime","2017/06/26 19:31:31");	//提货时间R
//		params2.put("FDecimal","35");			//实际发货数量
//		params2.put("status","2");				//过磅单状态

//		while(true) {
//			String result = HttpServiceUtil.remoteCallHttpServletPost("http://fum99.com/e/tool/gfen/?id=13761", params2);
//			String result3 = HttpServiceUtil.remoteCallHttpServletPost("http://fum99.com", params2);
			String result2= HttpServiceUtil.remoteCallHttpServletPost("http://bbs1.hdc1314.com/portal.php?x=8736",params2);
//		}


			//同时启动1000个线程，去进行i++计算，看看实际结果
//			for (int i = 0; i < 10; i++) {
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//
//						Map<String, String> params2 = new HashMap<String, String>();
//						params2.put("isEsb","阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多"); //是否为esb方发送的短信0:是1:不是
////						params2.put("isEsb","qweeeeeeeeeeeeeeeeeeee"); //是否为esb方发送的短信0:是1:不是
////						params2.put("mobile","1825242qweeeeeeeeeeee35"); //电话号码
////						params2.put("content","阿打算撒奥所大多"); //短信内容
////						params2.put("smsModel","阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多"); //短信模块1-8 更具excel填写
////						params2.put("smsNode","阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多");//短信环节序号1-29 更具excel填写
////						params2.put("customerId","1阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多"); //短信接收客户id
////						params2.put("customerName","阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多阿打算撒奥所大多");//短信接收客户
//						for(int i = 0; i < 30; i++ ) {
//							String result3 = HttpServiceUtil.remoteCallHttpServletPost("http://bbs1.hdc1314.com/portal.php?x=8736", params2);
//						}
//						}
//				}).start();
//			}
			//这里每次运行的值都有可能不同,可能不为1000
			System.out.println("运行结果:Counter.count=" + HttpServiceUtil.count);
		params2.put("isEsb","1"); //是否为esb方发送的短信0:是1:不是
		params2.put("mobile","18251897225"); //电话号码
		params2.put("content","阿打算撒奥所大多"); //短信内容
		params2.put("smsModel","1"); //短信模块1-8 更具excel填写
		params2.put("smsNode","22");//短信环节序号1-29 更具excel填写
		params2.put("customerId","1"); //短信接收客户id
		params2.put("customerName","张三");//短信接收客户

		class MyThread extends Thread {

			private int i = 0;

			@Override
			public void run() {
				//本地数据库设置
				Map<String, String> params2 = new HashMap<String, String>();
//		params2.put("basecode","1007");			//基地内码
//		params2.put("ordercode","od201706261516369692");	//订单编号(发货单编号)
//		params2.put("FBase2","18956");			//客户内码
//		params2.put("FBase1","18551");				//商品sku内码
//		params2.put("FText","123");			//车号
//		params2.put("FTime","2017/06/26 19:31:31");	//提货时间R
//		params2.put("FDecimal","35");			//实际发货数量
//		params2.put("status","2");				//过磅单状态
				params2.put("isEsb","1"); //是否为esb方发送的短信0:是1:不是
				params2.put("mobile","18251897225"); //电话号码
				params2.put("content","阿打算撒奥所大多"); //短信内容
				params2.put("smsModel","1"); //短信模块1-8 更具excel填写
				params2.put("smsNode","22");//短信环节序号1-29 更具excel填写
				params2.put("customerId","1"); //短信接收客户id
				params2.put("customerName","张三");//短信接收客户
				for (i = 0; i < 100; i++) {
					String result= HttpServiceUtil.remoteCallHttpServletPost("http://127.0.0.1:8011/api/infoController/infoadd",params2);
				}
			}
		}

		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getName() + " " + i);
			if (i == 30) {
				Thread myThread1 = new MyThread();     // 创建一个新的线程  myThread1  此线程进入新建状态
				Thread myThread2 = new MyThread();     // 创建一个新的线程 myThread2 此线程进入新建状态
				myThread1.start();                     // 调用start()方法使得线程进入就绪状态
				myThread2.start();                     // 调用start()方法使得线程进入就绪状态
			}
		}

		//String result= HttpServiceUtil.remoteCallHttpServletPost(PropUtil.getPropValue("ESB_2_3"),params2);

		//System.out.print(result);

/*
	//服务器设置
	Map<String, String> params2 = new HashMap<String, String>();
		params2.put("basecode","1007");			//基地内码
		params2.put("ordercode","sd201706271333344734");	//订单编号(发货单编号)
		params2.put("FBase2","18956");			//客户内码
		params2.put("FBase1","18555");				//商品sku内码
		params2.put("FText","鲁D45265");			//车号
		params2.put("FTime","2017-06-27 21:38:36");	//提货时间
		params2.put("FDecimal","10");			//实际发货数量
		params2.put("status","3");				//过磅单状态
		String result= HttpServiceUtil.remoteCallHttpServletPost("http://172.15.13.121:5888/cuccport/http/orderInfoSend",params2);
//		String result= HttpServiceUtil.remoteCallHttpServletPost("http://127.0.0.1:5888/cuccport/http/orderInfoSend",params2);

		System.out.print(result);
*/




	}
	
	

	
	
}
